<% extends "common/msui.html" %>
<% block title %>首页<% endblock %>
<% set images = _pool['product.template'].get_images_for_index() %>
<% set events = _pool['product.template'].get_events_for_index() %>
<% block body %>
<div class="page" id='home-index' ms-controller='home' >
  <header class="bar bar-nav">
    <a class='button button-link button-nav pull-right' style='margin-right:5px' ms-visible="visible=='cart' && cart.editable" ms-click='editable_done'><span>完成</span></a>
    <a class='button button-link button-nav pull-right' style='margin-right:5px' ms-visible="visible=='cart' && !cart.editable" ms-click='enter_editable'><span>编辑</span></a>
    <a class='button button-link button-nav pull-left' style='margin-left:5px' ms-visible="visible=='cart' && cart.editable" ms-click='editable_give_up'><span>放弃</span></a>
    <h1 class="title">{{title}}</h1>
  </header>

  <div class="content">
    <div ms-visible="visible=='index'">
      <div id="slide_gallery" class="focus">
        <div class="hd">
          <ul></ul>
        </div>
        <div class="bd">
          <ul>
            <% for image in images %>
              <!-- 需要一个维护首页图片的地方 -->
              <li><a href="${image.url | safe}"><img _src="${image.image}"/> </a></li>
            <% endfor %>
          </ul>
        </div>
      </div>

      <div class='header-search'>
        <div class='form' id='searchForm' name='searchForm'>
          <div class='search-word'>
            <input type='text' class='input' autocomplete='off' name='word' id='search-word' placeholder='请输入关键词' />
          </div>
          <div class='submit' href='#' id='search-submit'>
           <span class="ico-search" ></span>
          </div>
        </div>
      </div>

      <div class='index-gallery-categ'>
        <ul>
          <!-- <li><a href='/mshop/products'><span class='icon icon-product'></span><span>全部商品</span> </a></li><li><a href='/mshop/order'><span class='icon icon-order'></span><span>我的订单</span> </a></li><li><a href='#'><span class='icon icon-tuan'></span><span>最新团购</span> </a></li><li><a href='/mshop/brand'><span class='icon icon-ping'></span><span>品牌馆</span> </a></li> -->
          <li><a href='/mshop/products'><span class='icon icon-product'></span><span>全部商品</span> </a></li><li><a href='/mshop/order'><span class='icon icon-order'></span><span>我的订单</span> </a></li><li><a href='/mshop/category'><span class='icon icon-categ'></span><span>产品分类</span> </a></li><li><a href='#'><span class='icon icon-tuan'></span><span>最新团购</span> </a></li>
        </ul>

        <!-- <ul> -->
          <!-- <li><a href='/mshop/category'><span class='icon icon-categ'></span><span>产品分类</span> </a></li><li><a href='/mshop/search'><span class='icon icon-hot-search'></span><span>热门搜索</span> </a></li><li><a href='/mshop/shopping_cart'><span class='icon icon-shopping-cart'></span><span>购物车</span> </a></li><li><a href='/mshop/my'><span class='icon icon-person'></span><span>个人中心</span> </a></li> -->
        <!-- </ul> -->
      </div>

      <!-- 需要获取一个实际的图片墙列表，其中数据结构为[{mode: '', small_1: {url: '', img: ''}, small_2: {url: '', img: ''}, small_3: {url: '', img: ''}}] -->

      <div class='index-gallery-content'>
        <% for event in events %>
          <div class='index-gallery-content-show'>

            <% if event.mode == 'mix' %>
              <div class='index-gallery-content-show-gather_three' >
                <div class='gallery-vertical-big'>
                  <a href='${event.small_3.url}'><img src='${event.small_3.img}' /></a>
                </div><div class='gallery-vertical-small'>
                  <p><a href='${event.small_1.url}'><img src='${event.small_1.img}' /></a></p>
                  <p><a href='${event.small_2.url}'><img src='${event.small_2.img}' /></a></p>
                </div>
              </div>
            <% endif %>

            <% if event.mode == 'horizontal' %>
              <div class='index-gallery-content-show-gather_two' >
                <div>
                  <a href='${event.small_1.url}'><img src='${event.small_1.img}' /></a>
                </div><div >
                  <a href='${event.small_2.url}'><img src='${event.small_2.img}' /></a>
                </div>
              </div>
            <% endif %>

            <% if event.mode == 'single' %>
              <div class='index-gallery-content-show-alone' >
                <div class='gallery-horizontal-big'>
                  <a href='${event.small_1.url}'><img src='${event.small_1.img}' /></a>
                </div>
              </div>
            <% endif %>

          </div>
        <% endfor %>
      </div>
    </div>

    <div class='content' ms-visible="visible=='cart'">
      <div class="list-block cards-list" style='margin-bottom:100px;margin-top:0px'>
        <ul>
          <li ms-repeat='cart.cart_line' class='card' ms-visible="el.state == 'draft'" >
            <div class='card-header wrap-hidden'>{{el.product_name}}</div>
            <div class="item-content" style='padding-left:0px;'>

              <div class='col-5' style='margin-left:5px;margin-right:10px' ms-click='choose_line(el)' >
                <div class='circle-choose' ms-class='circle-choosed:el.choose'></div>
              </div>

              <div class='item-media'><img ms-attr-src='/website/image/product.product/{{el.product_id}}/image' width='60rem' height='40rem' /></div>
              <div class='item-inner' style='display:inline-block' ms-active='cart-line-active'>
                <div class='row'>
                  <div class='inner-left-content col-95' style='margin-left:0px'>
                    <ul style='padding-left:0.5rem;'>
                      <li><span>{{el.name}} </span></li>
                      <li>
                        <span>{{el.price_unit}} ¥</span>
                        <div ms-if='el.product_group' style='display:inline'><span>({{el.reserve_quantity}}</span> / <span style='color:red'>{{el.minimum_quantity}})</span></div>
                      </li>
                      <li>
                        <div class='control-qty'>
                          <span ms-click='mins_qty(el, el.product_uom_qty)' class='mshop-minus-qty' ms-class='mshop-minus-qty-disable:el.product_uom_qty <= 1'>-</span><input ms-attr-readonly='!cart.editable' class='mshop-qty' ms-duplex='el.product_uom_qty' type='text' autocomplete='off' /><span ms-click='plus_qty(el)' class='mshop-plus-qty'>+</span>
                        </div>
                      </li>
                    </ul>
                  </div>

                  <div class='col-20 editable-delete-right' ms-visible='cart.editable' ms-click='delete_line(el)'>
                    <p>删除</p>
                  </div>

                </div>
              </div>
            </div>
          </li>
        </ul>
      </div>

      <div class='card mshop-tab-card mshop-releative-top'>
        <div class='card-content'>
          <div class='card-content-inner' style='padding-top:0px;padding-bottom:0px'>
            <div class='row'>
              <div class='col-5' style='margin-left:15px;margin-top:4px;padding-top:15px;padding-bottom:15px' ms-click='all_choose_line()'>
                <div class='circle-choose' ms-class='circle-choosed:cart.all_choose'></div>
              </div>

              <div class='col-10' style='padding-top:15px;padding-bottom:15px' ><span style='white-space:nowrap'>全选</span></div>

              <div class='col-20 pull-right mshop-clearing' ms-click='clearing_cart' ms-class='mshop-clearing-disable:cart.disable_clearing'><span>结算</span></div>
              <div class='col-20 pull-right' style='padding-top:15px;padding-bottom:15px'><span style='white-space:nowrap;float:right'>合计: {{cart.amount}} ¥</span></div>

            </div>
          </div>
        </div>
      </div>

    </div>

    <div ms-if="visible=='my'">
      <a ms-attr-href='/mshop/my/info?partner_id={{my.partner_id}}'>
        <div class='my-picture' >
          <img id='image' src='/website/image/res.partner/{{my.partner_id}}/image' />
          <div>{{my.name}}</div>
        </div>
      </a>

      <div class='my-order'>
        <div class='my-order-all'>
          <span>全部订单</span><span ><a href='/mshop/order'>查看全部订单 ></a></span>
        </div>

        <hr />
        <div class='my-order-list'>
          <ul>
            <li><a href='/mshop/order?state=draft'><span class='icon icon-edit'></span><span>待确认({{my.counts.confirm_count}})</span></li></a>
            <!-- <li><a href='/mshop/order?state=confirmed'><span class='icon icon-card'></span><span>已确认</span></li></a> -->
            <!-- 似乎暂时没有状态可以区分不同单据的付款去发货状态 -->
            <li><a href='/mshop/order?state=progress,manual'><span class='icon icon-gift'></span><span>待收货({{my.counts.stock_count}})</span></li></a>
            <li><a href='/mshop/order?state=done'><span class='icon icon-message'></span><span>待评价({{my.counts.evaluation_count}})</span></li></a>
          </ul>
        </div>
      </div>

      <div class='my-order-address'>
        <span>默认地址</span>
        <hr>
        <div class='media-list list-block order-address' >
          <a href="/mshop/customer/address" class="item-link item-content order-address-content">
            <div class="item-inner">
              <div class="item-title-row">
                <div class="item-title"><span>收货人：</span>{{my.address.name}}</div>
                <div class="item-after">{{my.address.phone}}</div>
              </div>
              <div class='item-text'><span>{{my.address.province}}{{my.address.city}}{{my.address.country}} {{my.address.street}}</span></div>
            </div>
          </a>
        </div>
      </div>
    </div>

  </div>

  <footer>
    <nav class="bar bar-tab index-footer">
      <a class="tab-item" ms-class="active:visible=='index'" ms-click="change_page('index')">
        <span class="icon icon-home"></span>
        <span class="tab-label">首页</span>
      </a>
      <a class="tab-item" ms-class="active:visible=='cart'" ms-click="change_page('cart')">
        <span class="icon icon-cart"></span>
        <span class="tab-label">购物车</span>
      </a>
      <a class="tab-item" ms-class="active:visible=='my'" ms-click="change_page('my')">
        <span class="icon icon-me"></span>
        <span class="tab-label">我的</span>
      </a>
    </nav>
  </footer>

  <script type="application/javascript">

  $(function() {

    var events = ${events | tojson | safe};
    var tab = '${tab | safe}' || 'index';
    var cart_line = [];

    cart_line.forEach(function(line) {
      line.name = line.name.substr(0, 50) + '...';
      line.choose = false;
    });


    var update_cart_line = function(line_id, qty) {
      $.ajax({
        url: '/mshop/shopping_cart/update_cart',
        data: {
          line_id: line_id,
          qty: qty,
        },
        async: true,
      });
    };

    var synchronize_cart_line = function(cart_line) {
      var change_line = {}
      home_vm.cart.cart_line.forEach(function(line) {
        change_line[line.id] = {
          state: line.state,
          product_uom_qty: line.product_uom_qty,
      }});

      $.ajax({
        url: '/mshop/shopping_cart/update_cart',
        data: {
          cart_line: JSON.stringify(change_line),
        },
        type: 'post',
        async: true,
      });

    };

    $('#search-word').keydown(function(e) {
      if (e.keyCode === 13) {
        var key = $('#search-word').val();
        $.router.loadPage('/mshop/search?word=' + key);
      }
    });

    // 代码会被多次调用
    $('#search-submit').click(function(e) {
      var key = $('#search-word').val();
      if (key) {
        $.router.loadPage('/mshop/search?word=' + key);
      };
    });

    try {
      TouchSlide({
          slideCell: "#slide_gallery",
          titCell: ".hd ul", //开启自动分页 autoPage:true ，此时设置 titCell 为导航元素包裹层
          mainCell: ".bd ul",
          effect: "left",
          autoPlay: true, //自动播放
          autoPage: true, //自动分页
          switchLoad: "_src" //切换加载，真实图片路径为"_src"
      });
    } catch(error) {
      console.log('显示图片错误，可能图片没有被被加载');
    }

    setTimeout(function() {
        $('.tempWrap').trigger('resize')
    }, 100);

    var sync_content = function(page) {
      if (page === 'cart' && home_vm.cart.init === true) {
        $.get('/mshop/shopping_cart/get', function(e) {
          var response = JSON.parse(e);
          home_vm.cart.cart_line = response;
          home_vm.cart.init = false;
        });
      } else if (page === 'my' && home_vm.my.init === true) {
        $.get('/mshop/my/get', function(e) {
          var res = JSON.parse(e);
          home_vm.my.name = res.name;
          home_vm.my.address = res.address;
          home_vm.my.counts = res.counts;
          home_vm.my.partner_id = res.partner_id;
          home_vm.my.init = false;
        });
      };
    };

    var home_vm = avalon.define({
      $id: 'home',
      visible: 'index',
      title: '首页',
      cart: {editable: false, disable_clearing: true, all_choose: false, cart_line: [], amount: 0, backup_cart_line: [], init: true},
      my: {name: '', address: {}, counts: {}, partner_id: '', init: true},

      change_page: function(page) {
        var title_map = {
          index: '首页',
          cart: '购物车',
          my: '我的'
        };

        home_vm.visible = page;
        home_vm.title = title_map[page];
        sync_content(page);
      },
      update_amount: function() {
        home_vm.cart.amount = 0;
        home_vm.cart.cart_line.forEach(function(line) {
          if (line.choose && line.state == 'draft') {
            home_vm.cart.amount += line.product_uom_qty * line.price_unit
          }
        });
      },
      mins_qty: function(line, qty) {
        if (parseInt(line.product_uom_qty) > 1) {
          line.product_uom_qty = parseInt(line.product_uom_qty) - 1;
          update_cart_line(line.id, line.product_uom_qty);
          home_vm.update_amount();
        }
      },

      plus_qty: function(line) {
        line.product_uom_qty = parseInt(line.product_uom_qty) + 1;
        update_cart_line(line.id, line.product_uom_qty);
        home_vm.update_amount();
      },

      enter_editable: function() {
        home_vm.cart.editable = true;
        // home_vm.cart.backup_cart_line = home_vm.cart.cart_line;
        // 将进入编辑状态前每行的数量和状态记录下来
        home_vm.cart.backup_cart_line = []
        $.each(home_vm.cart.cart_line, function(index) {
          home_vm.cart.backup_cart_line.push({
            index: index,
            state: home_vm.cart.cart_line[index].state,
            product_uom_qty: home_vm.cart.cart_line[index].product_uom_qty,
          });
        });

        $('.inner-left-content').addClass('col-80');
      },

      editable_give_up: function() {
        home_vm.cart.editable = false;

        home_vm.cart.backup_cart_line.forEach(function(line) {
          $.extend(true, home_vm.cart.cart_line[line.index], line)
        });
      },

      editable_done: function() {
        home_vm.cart.editable = false;
        synchronize_cart_line(home_vm.cart.cart_line);
        $('.inner-left-content').removeClass('col-80');
      },

      delete_line: function(line) {
        line.state = 'delete';
      },

      choose_line: function(line) {
        line.choose = !line.choose;

        home_vm.cart.all_choose = true;
        home_vm.cart.disable_clearing = true;

        home_vm.cart.cart_line.forEach(function(line) {
          if (!line.choose) {
            home_vm.cart.all_choose = false;
          } else {
            home_vm.cart.disable_clearing = false;
          }
        });

        home_vm.update_amount();
      },

      all_choose_line: function() {
        home_vm.cart.all_choose = !home_vm.cart.all_choose;
        home_vm.cart.disable_clearing = !home_vm.cart.all_choose;
        if (home_vm.cart.cart_line.length === 0) home_vm.cart.disable_clearing = true;

        home_vm.cart.cart_line.forEach(function(line) {
          line.choose = home_vm.cart.all_choose;
        });

        home_vm.update_amount();
      },

      clearing_cart: function() {
        if (home_vm.cart.disable_clearing) {
          return;
        }

        var line_ids = [];
        try {
          home_vm.cart.cart_line.forEach(function(line){
            if (line.choose && line.state == 'draft') {
                if (line.product_group && line.reserve_quantity < line.minimum_quantity) {
                  $.alert('抱歉，' + line.product_name + '的预订数量还没有达到起订数量');
                  throw {'name': 'error'};
                };
              line_ids.push(line.id);
            }
          });
        } catch(e) {
          return;
        }

        $.ajax({
          url: '/mshop/shopping_cart/clearing',
          data: {
            line: JSON.stringify(line_ids),
          },
          type: 'post',
          success: function(e) {
            $.router.loadPage('/mshop/order?order_id=' + e);
          },
          async: true,
        });
      }});

      home_vm.change_page(tab);
      avalon.scan();
  });
  </script>
</div>
<% endblock %>